<?php

namespace App\Http\Controllers;

use App\Http\Requests\EditUserInfoRequest;
use App\Http\Requests\UserInfoRequest;
use App\MakeTable\Table;
use App\Redict\Success;
use App\Role;
use App\User;


class UserController extends Controller
{
    //
    //
    public function __construct()
    {
//        $this->middleware('can:users_permissions');
    }

    public function index(){

        $pagename = '管理员列表';
        $modelurl = 'users';
        $tablecate = ['tablecate'=>'管理员'];
        $headname = ['姓名','备注','电话','真实姓名','邮箱','角色','账号创建日期','操作'];
        $tablehead = ['name','grade','tele','truename','email','roles','created_at','id'];
        $usertable = new Table($tablehead,$page = 5);
        $model = $usertable->viewdata(User::class);
        $models = $usertable->viewpagedata(User::class);


        return view('admin.home.tableshow',compact('tablecate','model','tablehead','models','headname','pagename','modelurl'));
    }
    public function create(){
        $modelurl = 'users';
        $pagename = '添加管理员';
        $roles = Role::all()->pluck('label','id');
        return view('admin.home.userform',compact('pagename','roles','modelurl'));
    }
    public function store(UserInfoRequest $request){

        $user = User::create($request->all());
        $user->roles()->attach($request->input('roles_list'));

        return redirect('admin/users')->with('message', '成功添加'.$user->name);
    }
    public function edit($id){
        $modelurl = 'users';
        $user = User::findOrFail($id);
        $roles_list = collect($user->roles->pluck('id'))->toArray();
        $pagename = $user->name;
        $roles = Role::all()->pluck('label','id');

        return view('admin.home.useredit',compact('pagename','roles','user','roles_list','modelurl'));
    }
    public function update(EditUserInfoRequest $request,$id){
        $user = User::findOrFail($id);
        $input = $request->input('roles_list');
        $now = collect($user->roles->pluck('id'))->toArray();
        $user->roles()->attach(collect($input)->diff($now)->toArray());
        $user->roles()->detach(collect($now)->diff($input)->toArray());

        $user->update($request->all());

        return Success::back();
    }
    public function destroy($id){
        $user = User::findOrFail($id);
        $user->delete();
        return Success::back();
    }
}
